<script setup>
import { computed } from 'vue';

const props = defineProps({
  r1: { type: Number, default: 0 }, // 去年
  r2: { type: Number, default: 0 }, // 今年
});
// 计算同比变化百分比
const changeInfo = computed(() => {
  const { r1, r2 } = props;
  if (r2 === 0 || `${r1}` === 'NaN' || `${r2}` === 'NaN') {
    return {
      text1: ' ',
      text2: '?',
      color: 'text-yellow-500',
    };
  }

  const diff = r1 - r2;
  const percentage = (diff / Math.abs(r2)) * 100;
  const percentText = `${Math.abs(percentage).toFixed(2)}%`;

  if (`${percentage}` === 'NaN') {
    return {
      text1: ' ',
      text2: '?',
      color: 'text-yellow-500',
    };
  } else if (percentage > 0) {
    return {
      text1: `↑ `,
      text2: percentText,
      color: 'text-red-500',
    };
  } else if (percentage < 0) {
    return {
      text1: `↓ `,
      text2: percentText,
      color: 'text-green-500',
    };
  } else {
    return {
      text1: '',
      text2: '0.00%',
      color: 'text-gray-500',
    };
  }
});
</script>

<template>
  <div class="flex items-center justify-end text-sm">
    <span :class="changeInfo.color" class="scale-75 pb-1">{{
      changeInfo.text1
    }}</span>
    <span :class="changeInfo.color">{{ changeInfo.text2 }}</span>
  </div>
</template>
